package com.itheima.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.goods.dao.SpecMapper;
import com.itheima.goods.pojo.Spec;
import com.itheima.goods.service.SpecService;
import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SpecServiceImpl extends ServiceImpl<SpecMapper, Spec> implements SpecService {
    @Autowired
    SpecMapper specMapper;

    @Override
    public List<Spec> findAll() {
        LambdaQueryWrapper<Spec> wrapper = Wrappers.<Spec>lambdaQuery();
        //获取原始多种option数据
        List<Spec> list = specMapper.selectList(wrapper);
        //新建一个list接收分割option后的数据
        List<Spec> specs = new ArrayList<>();
        //遍历原始数据
        for (Spec spec : list) {
            //切割option
            String[] options = spec.getOptions().split(",");
            //遍历option数组
            for (String option : options) {
                //创建spec对象,传入参数
                Spec newSpec = new Spec(spec.getId(), spec.getName(), option, spec.getSeq());
                //把新的spec传入新的集合
                specs.add(newSpec);
            }
        }

        //返回分割后的集合
        return specs;

    }

    @Override
    public PageResult findPage(Integer page, Integer size, Map<String, String> searchMap) {
        LambdaQueryWrapper<Spec> wrapper = Wrappers.<Spec>lambdaQuery();
        if (searchMap.get("name") != null && searchMap.get("name").length() > 0) {
            wrapper.like(Spec::getName, searchMap.get("name"));
        }
        if (searchMap.get("options") != null && searchMap.get("options").length() > 0) {
            wrapper.like(Spec::getOptions, searchMap.get("options"));
        }
        if (searchMap.get("seq") != null) {
            wrapper.eq(Spec::getSeq, searchMap.get("seq"));
        }
        Page<Spec> specPage = specMapper.selectPage(new Page<>(page, size), wrapper);
        PageResult<Spec> specPageResult = new PageResult<>();
        specPageResult.setTotal(specPage.getTotal());
        specPageResult.setRows(specPage.getRecords());
        return specPageResult;

    }
}
